<?php

/**
 *  用户行为
 * @author xiaojy xiaojy@wanthings.com
 * @copyright 成都网信天成科技有限公司, 2016, http://www.wanthings.com
 */
class UserBehavior extends CActiveRecordBehavior
{

    /**
     * @param array $user 用户信息数组，电话，密码。
     * @return bool true false.
     *
     */
    public function getList($filter)
    {
        $result = array();
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => 0));

        if (!empty($filter['sid'])) {
            $criteria->addCondition('sid=' . $filter['sid']);
        }

        if (!empty($filter['ids'])) {    //能够选择的ids
            $criteria->addInCondition('sid', $filter['ids']);
        }

        if (!empty($filter['mobile'])) {
            $mobile = $filter['mobile'];
            $criteria->compare('mobile', $mobile, true, 'AND');
        }
        if (!empty($filter['min_time']) || !empty($filter['max_time'])) {
            if (!empty($filter['min_time']) && !empty($filter['max_time'])) {
                $criteria->addBetweenCondition('ctime', $filter['min_time'], $filter['max_time']);
            } elseif (!empty($filter['min_time']) && empty($filter['max_time'])) {
                $criteria->addCondition('ctime>' . $filter['min_time']);
            } else {
                $criteria->addCondition('ctime<=' . $filter['max_time']);
            }

        }
        if (isset($filter['style'])) {
            if ($filter['style'] == 1) {
                $criteria->order = 'id desc';
            } else {
                $criteria->order = 'id desc';
            }
        } else {
            $criteria->order = 'id desc';
        }

        if (!empty($filter['page']) || !empty($filter['page_size'])) {
            if (!empty($filter['page'])) {
                $page = $filter['page'];
            } else {
                $page = 1;
            }
            if (!empty($filter['page_size'])) {
                $page_size = $filter['page_size'];
            } else {
                $page_size = 20;
            }
            $count = $this->owner->model()->count($criteria);
            $pager = new CPagination($count);
            $pager->setItemCount($count);
            $pager->setCurrentPage($page - 1);
            $pager->setPageSize($page_size);
            $pager->validateCurrentPage = false;
            $pager->applyLimit($criteria);
            $result['pager'] = $pager;
        }
        $result['data'] = array();
        $query_result = $this->owner->findAll($criteria);
        if (!empty($query_result)) {
            foreach ($query_result as $key => $value) {
                $temp = $value->attributes;
                $result['data'][] = $temp;
            }
        }

        return $result;
    }


    private function findBySid($sid)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('sid' => $sid, 'is_deleted' => 0));
        $re = $this->owner->find($criteria);
        return $re;
    }


    private function findById($id)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('id' => $id, 'is_deleted' => 0));
        $re = $this->owner->find($criteria);
        return $re;
    }

    private function findByMobile($mobile)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('mobile' => $mobile, 'is_deleted' => 0));
        $re = $this->owner->find($criteria);
        return $re;
    }


    /**
     * @param array $user 用户信息数组，电话，密码。
     * @return bool true false.
     *
     */
    public function signUp($user)
    {

        $re = $this->checkMobile($user['mobile']);
        if (!empty($re)) {
            $result['errno'] = 3111;
            $result['errmsg'] = '电话号码已注册';
            $result['result'] = '';
            return $result;
        } else {
            $ma = new User;
            //默认配置
            $ma->sid = WxUtil::create_uuid();
            if (!empty($user['mobile'])) {
                $ma->mobile = $user['mobile'];
            } else {
                $result['errno'] = 3106;
                $result['errmsg'] = '电话号码未填写';
                $result['result'] = '';
                return $result;
            }
            if (!empty($user['password'])) {
                $ma->password = User::model()->setPassword($user['password']);
            } else {
                $result['errno'] = 3107;
                $result['errmsg'] = '密码未填写';
                $result['result'] = '';
                return $result;
            }
            if ($ma->save()) {
                $sid = $ma->sid;
                if (isset($user['app_id'])) {
                    $app_id = $user['app_id'];
                } else {
                    $app_id = 1;
                }
                $re = UserToken::model()->genToken($sid, $app_id, !YII_DEBUG);
                $result['errno'] = 0;
                $result['errmsg'] = '';
                $result['result'] = $sid;
                return $result;
            } else {
                $result['errno'] = 3108;
                $result['errmsg'] = '保存失败';
                $result['result'] = '';
                return $result;
            }
        }
    }

    /**
     *检查短信验证码
     * @param $captcha 验证短信验证码
     * @return bool true false.
     *
     */
    public function checkCaptcha($captcha, $mobile)
    {
        if (!empty($mobile)) {
            if ($captcha == Yii::app()->cache->get('captcha_' . $mobile)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function getStatusText($status)
    {
        $text = '';
        if ($status == 1) {
            $text = '正常';
        } elseif ($status == 2) {
            $text = '禁用';
        } else {

        }
        return $text;
    }

    public function checkMobile($mobile)
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => '0', 'mobile' => $mobile));
        $re = $this->owner->find($criteria);
        if ($re) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * @param array $user 用户信息数组，mobile ,password ,captcha
     * @return bool true false.
     *
     */
    public function retrievePassword($user)
    {
        $result = array();
        if (empty($user['mobile']) || empty($user['password']) || empty($user['captcha'])) {
            $result['errno'] = 3124;
            $result['errmsg'] = '参数不足';
            $result['result'] = '';
            return $result;
        }

        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => '0', 'mobile' => $user['mobile']));
        $re = $this->owner->find($criteria);
        if (!empty($re)) {
            if (!empty($user['captcha'])) {

                if ($user['captcha'] == Yii::app()->cache->get('captcha_' . $re->mobile)) {

                    if (isset($user['password'])) {
                        $re->password = User::model()->setPassword($user['password']);
                        if ($re->save()) {
                            $result['errno'] = 0;
                            $result['errmsg'] = '';
                            $result['result'] = '';
                            return $result;
                        } else {
                            $result['errno'] = 3100;
                            $result['errmsg'] = '保存失败';
                            $result['result'] = '';
                            return $result;
                        }

                    } else {
                        $result['errno'] = 3101;
                        $result['errmsg'] = '请输入密码';
                        $result['result'] = '';
                        return $result;
                    }

                } else {
                    $result['errno'] = 3103;
                    $result['errmsg'] = '验证码错误';
                    $result['result'] = '';
                    return $result;
                }
            } else {
                $result['errno'] = 3104;
                $result['errmsg'] = '请输入验证码';
                $result['result'] = '';
                //echo '验证码错误';
                return $result;
            }
        } else {
            $result['errno'] = 3105;
            $result['errmsg'] = '手机号未注册';
            $result['result'] = '';
            return $result;
        }

    }


    /**
     * @param $sid 用户sid
     * @return 用户信息数组.
     */
    public function getBySid($sid)
    {
        $result = array();
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('sid' => $sid, 'is_deleted' => 0));
        $re = $this->owner->model()->find($criteria);
        if (!empty($re)) {
            $temp = $re->attributes;
            $result['errno'] = 0;
            $result['errmsg'] = '';
            return $result;
        } else {
            $result['errno'] = 3126;
            $result['message'] = '用户不存在';
            $result['result'] = '';
            return $result;
        }
    }


    /**
     * @param $id 用户id
     * @return 用户信息数组.
     */
    public function getById($id)
    {
        $result = array();

        $re = $this->findById($id);
        if (!empty($re)) {
            $a = $re->attributes;
            $result['errno'] = 0;
            $result['errmsg'] = '';

            return $result;
        } else {
            $result['errno'] = 3126;
            $result['errmsg'] = '用户不存在';
            $result['result'] = '';
            return $result;
        }
    }


    /**
     * @param $id 用户id
     * @return 用户信息数组.
     */
    public function getByMobile($mobile)
    {
        $result = array();
        $re = $this->findByMobile($mobile);
        if (!empty($re)) {
            $a = $re->attributes;
            $result['errno'] = 0;
            $result['errmsg'] = '';
            $result['result'] = $a;
            return $result;
        } else {
            $result['errno'] = 3126;
            $result['errmsg'] = '用户不存在';
            return $result;
        }
    }


    //删除
    public function deleteBySid($sid)
    {
        $result = array();
        $re = $this->findBySid($sid);
        if (!empty($re)) {
            $re->is_deleted = 1;
            $status = $re->save();
            if ($status) {
                $result['errno'] = 0;
                $result['errmsg'] = '';
            } else {
                $result['errno'] = 3125;
                $result['errmsg'] = '删除失败';
            }
            return $result;

        } else {
            $result['errno'] = 4355;
            $result['errmsg'] = '用户不存在';
            return $result;
        }
    }


    //根据传入参数切换状态
    public function setStatus($sid, $status)
    {
        $result = array();
        $re = $this->findBySid($sid);
        if (!empty($re)) {
            $re->status = $status;
            $temp = $re->save();
            if ($temp) {
                $result['errno'] = 0;
                $result['errmsg'] = 'success';
                return $result;
            } else {
                $result['errno'] = 3100;
                $result['errmsg'] = '保存失败';
                return $result;
            }
        } else {
            $result['errno'] = 3124;
            $result['errmsg'] = '未找到该用户';
            return $result;
        }
    }


    public function getStatus($sid)
    {
        $result = array();
        $re = $this->findBySid($sid);
        if ($re) {
            $result['errno'] = 0;
            $result['errmsg'] = '';
            $result['result'] = $re->status;
            return $result;
        } else {
            $result['errno'] = 3100;
            $result['errmsg'] = '没有该用户';
            $result['result'] = '';
            return $result;
        }
    }


    /**
     * @param $user 用户信息数组 ，
     * @param  name 姓名 ，student_no 学生号 gender性别
     * @param  idcard 身份证号
     * @param  nickname 昵称
     * @return boolean whether authentication succeeds.
     */
    public function add($user)
    {
        if (empty($user['mobile'])) {
            $result['errno'] = 3132;
            $result['errmsg'] = '参数不足';
            return $result;
        }
        $re = $this->checkMobile($user['mobile']);
        if (!empty($re)) {
            $result['errno'] = 3131;
            $result['errmsg'] = '手机号已注册';
            return $result;
        } else {
            $ma = new User;
            $ma->sid = WxUtil::create_uuid();

            $ma->mobile = $user['mobile'];
            if (!empty($user['password'])) {
                $ma->password = User::model()->setPassword($user['password']);
            } else {
                $ma->password = User::model()->setPassword(User::DEFAULT_PASSWORD);
            }

            $msg = array();
            if ($ma->save()) {
                $sid = $ma->sid;
                if (isset($user['app_id'])) {
                    $app_id = $user['app_id'];
                    $re = UserToken::model()->genToken($sid, $app_id);
                } else {
                    $re = UserToken::model()->genToken($sid, null);
                }

                $result['errno'] = 0;
                $result['errmsg'] = '';
                $result['result'] = $ma->attributes;
                return $result;
            } else {
                $result['errno'] = 3127;
                $result['errmsg'] = '更新失败';
                return $result;
            }
        }

    }


    /**
     * @param $username 登录名 ，
     * @param  $password 密码
     * @return boolean whether authentication succeeds.
     */
    public function verify($username = null, $password = null)
    {
        if (empty($username) || empty($password)) {
            $result['errno'] = 3133;
            $result['errmsg'] = '参数不足';
            $result['result'] = '';
            return $result;
        }
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => 0,
            'mobile' => $username));
        $user = $this->owner->find($criteria);
        if ($user === null) {
            $result['errno'] = 3124;
            $result['errmsg'] = '账号或密码错误';
            $result['result'] = '';
            return $result;
        } else if ($user['password'] != User::model()->setPassword($password)) {
            $result['errno'] = 3130;
            $result['errmsg'] = '账号或密码错误';
            $result['result'] = '';
            return $result;
        } else {
            $result['last_login_time'] = $user['last_login_time'];
            $re = $this->findBySid($user['sid']);
            $re->last_login_time = time();
            $re->save();
            $result['errno'] = 0;
            $result['errmsg'] = '';
            $result['result'] = $user->attributes;
            return $result;
        }
    }


    //获取所有用户sid
    public function getAllSid()
    {
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array());
        //只显示未删除的用户
        $criteria->addCondition('is_deleted=0');
        $re = $this->owner->findAll($criteria);
        $user = array();
        foreach ($re as $key => $value) {
            $user[] = $value->sid;
        }
        return $user;
    }

    public function getMobileBySid($sid)
    {
        $result = '';
        $user = $this->findBySid($sid);
        if (!empty($user)) {
            $result = $user->mobile;
        }
        return $result;
    }


    //计算密码强度
    public function setSafetyLevel($str)
    {
        $length = strlen($str);
        if ($length <= 6) {
            return 1;    //低
        } elseif ($length > 6 && $length < 10) {
            return 2;    //中
        } else {
            return 3;    //高
        }
    }


    //获取用户信息 强制使用缓存
    public function getCacheInfo($sid = 0)
    {
        $result = array();
        $cache_key = 'cache_data_user_info_id_' . $sid;
        $cache_data = Yii::app()->cache->get($cache_key);
        if (!empty($cache_data)) {
            return $cache_data;
        }
        $criteria = new CDbCriteria;
        $criteria->addColumnCondition(array('is_deleted' => 0));
        $criteria->addCondition('sid = ' . $sid);
        $data = $this->getOwner()->find($criteria);
        if (!empty($data)) {
            $result = $data->attributes;
            $result['avatar'] = WxUtil::getgoodsimgurl($result['avatar']);
        }
        Yii::app()->cache->set($cache_key, $result);
        return $result;
    }

    public function login($mobile, $password)
    {
        $result = array();

        $re = User::model()->verify($mobile, $password);
        if ($re['errno'] == 0) {
            $identity = new UserIdentity($mobile, $password);
            if ($identity->authenticate()) {
                $status = Yii::app()->user->login($identity, 3600 * 24 * 60);
                $sid = Yii::app()->user->getId();
            } else {
                $result['errno'] = 5463;
                $result['errmsg'] = '登录失败,可能是被禁用';
                return $result;
            }
        } else {
            $result['errno'] = 5736;
            $result['errmsg'] = '用户名或密码错误';
            return $result;
        }

    }

    public function checkMobileNo($mobile)
    {
        if (preg_match("/^1[34578]{1}\d{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }

    //生成随机数
    public function numRound($length = 6)
    {
        return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
    }


}

